package com.example.dangerouscargodriver.ui.activity;

import androidx.annotation.Nullable;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baiju.bean.CityBean;
import com.baiju.bean.ProvinceBean;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.baiju.style.wheelpicker.WheelPickerView;
import com.baiju.style.wheelpicker.bean.WheelItemBean;
import com.baiju.style.wheelpicker.config.WheelPickerConfig;
import com.baiju.style.wheelpicker.listener.OnWheelItemClickListener;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.controller.EnterPlatformInfoController;
import com.example.dangerouscargodriver.controller.IControllerEventListener;
import com.example.dangerouscargodriver.entry.CompanyInfo;
import com.example.dangerouscargodriver.entry.CompanyMainInfo;
import com.example.dangerouscargodriver.event.Event;
import com.example.dangerouscargodriver.event.LoadHttpResourceStatus;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.utils.AppManager;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.example.dangerouscargodriver.R;
import com.example.dangerouscargodriver.widget.LoadingDialog;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class CompanyAddLineInfoActivity extends HttpRequestActivity implements View.OnClickListener {

	private static final int START_ACTIVITY_FOR_LOAD_POSITION_ONE = 0;
	private static final int START_ACTIVITY_FOR_LOAD_POSITION_TWO = 1;
	private static final int START_ACTIVITY_FOR_LOAD_POSITION_THREE = 2;

	private static final int START_ACTIVITY_FOR_UNLOAD_POSITION_ONE = 3;
	private static final int START_ACTIVITY_FOR_UNLOAD_POSITION_TWO = 4;
	private static final int START_ACTIVITY_FOR_UNLOAD_POSITION_THREE = 5;
	private static final String TAG = "AddLineInfoActivity";
	private static final int MSG_LOAD_ENTER_ATTR_DONE = 0;

	private ActionBar mActionBar = null;

	private LinearLayout mLoadPositionOne = null;
	private LinearLayout mLoadPositionTwo = null;
	private LinearLayout mLoadPositionThree = null;

	private LinearLayout mUnLoadPositionOne = null;
	private LinearLayout mUnLoadPositionTwo = null;
	private LinearLayout mUnLoadPositionThree = null;

	private ImageView mIvLoadPositionOne = null;
	private TextView mTvLoadPositionOne = null;
	private ImageView mIvLoadPositionTwo = null;
	private TextView mTvLoadPositionTwo = null;
	private ImageView mIvLoadPositionThree = null;
	private TextView mTvLoadPositionThree = null;
	private ImageView mIvUnLoadPositionOne = null;
	private TextView mTvUnLoadPositionOne = null;
	private ImageView mIvUnLoadPositionTwo = null;
	private TextView mTvUnLoadPositionTwo = null;
	private ImageView mIvUnLoadPositionThree = null;
	private TextView mTvUnLoadPositionThree = null;

	//地址选择存储
	private ProvinceBean mSelectLoadProvinceOne = null;
	private CityBean mSelectLoadCityOne = null;

	private ProvinceBean mSelectLoadProvinceTwo = null;
	private CityBean mSelectLoadCityTwo = null;

	private ProvinceBean mSelectLoadProvinceThree = null;
	private CityBean mSelectLoadCityThree = null;

	private ProvinceBean mSelectUnLoadProvinceOne = null;
	private CityBean mSelectUnLoadCityOne = null;

	private ProvinceBean mSelectUnLoadProvinceTwo = null;
	private CityBean mSelectUnLoadCityTwo = null;

	private ProvinceBean mSelectUnLoadProvinceThree = null;
	private CityBean mSelectUnLoadCityThree = null;

	private Button mActionCommit = null;

	private LinearLayout mCompanySelector = null;
	private WheelPickerView mCompanyPickerView = null;
	private ArrayList<WheelItemBean> mCompanyList = null;
	private WheelItemBean mSelectedBean = null;
	private TextView mCompanyName = null;

	private MyHandler mHandler = null;
	private MyControllerEventListener mIControllerListener = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.initHttpComponent(CompanyAddLineInfoActivity.class);
		AppManager.getAppManager().addActivity(this);
		setContentView(R.layout.activity_add_line_info);
		mHandler = new MyHandler(this);
		mIControllerListener = new MyControllerEventListener();

		mLoadPositionOne = findViewById(R.id.layout_load_position_one);
		mLoadPositionOne.setOnClickListener(this);
		mLoadPositionTwo = findViewById(R.id.layout_load_position_two);
		mLoadPositionTwo.setOnClickListener(this);
		mLoadPositionThree = findViewById(R.id.layout_load_position_three);
		mLoadPositionThree.setOnClickListener(this);

		mUnLoadPositionOne = findViewById(R.id.layout_unload_position_one);
		mUnLoadPositionOne.setOnClickListener(this);
		mUnLoadPositionTwo = findViewById(R.id.layout_unload_position_two);
		mUnLoadPositionTwo.setOnClickListener(this);
		mUnLoadPositionThree = findViewById(R.id.layout_unload_position_three);
		mUnLoadPositionThree.setOnClickListener(this);

		mIvLoadPositionOne = findViewById(R.id.iv_load_position_one);
		mTvLoadPositionOne = findViewById(R.id.tv_load_position_one);
		mIvLoadPositionTwo = findViewById(R.id.iv_load_position_two);
		mTvLoadPositionTwo = findViewById(R.id.tv_load_position_two);
		mIvLoadPositionThree = findViewById(R.id.iv_load_position_three);
		mTvLoadPositionThree = findViewById(R.id.tv_load_position_three);

		mIvUnLoadPositionOne = findViewById(R.id.iv_unload_position_one);
		mTvUnLoadPositionOne = findViewById(R.id.tv_unload_position_one);
		mIvUnLoadPositionTwo = findViewById(R.id.iv_unload_position_two);
		mTvUnLoadPositionTwo = findViewById(R.id.tv_unload_position_two);
		mIvUnLoadPositionThree = findViewById(R.id.iv_unload_position_three);
		mTvUnLoadPositionThree = findViewById(R.id.tv_unload_position_three);

		mCompanySelector = findViewById(R.id.layout_company_belonged_to_selector);
		mCompanySelector.setOnClickListener(this);
		mCompanyPickerView = new WheelPickerView();
		mCompanyList = new ArrayList<WheelItemBean>();
		mCompanyPickerView.init(this, mCompanyList);

		mCompanyName = findViewById(R.id.tv_company_belonged_to);
		mCompanySelector = findViewById(R.id.layout_company_belonged_to_selector);
		mCompanySelector.setOnClickListener(this);

		mActionCommit = findViewById(R.id.btn_company_add_line);
		mActionCommit.setOnClickListener(this);
		mActionBar = findViewById(R.id.actionBarAddLineInfo);
		mActionBar.setOnBackClickListener( new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		EnterPlatformInfoController.Instance().attachControllerListener(CompanyAddLineInfoActivity.class,
				mIControllerListener);
	}

	private void initCompanyInfo(){
		List<CompanyInfo> companyInfos = EnterPlatformInfoController.Instance().getCompanyInfoList();

		if(companyInfos != null && companyInfos.size() > 0){
			mCompanyList.clear();
			for(int index = 0; index < companyInfos.size(); index++) {
				WheelItemBean bean = new WheelItemBean();
				bean.setId(companyInfos.get(index).getCid());
				bean.setName(companyInfos.get(index).getName());

				mCompanyList.add(bean);
			}
			mSelectedBean = mCompanyList.get(0);
		}
	}

	private void showCompanyListSelector(){
		if(mCompanyList.size() <= 0){
			ToastUtils.showLongToast(this, "获取公司信息异常！");
		}
		else{
			WheelPickerConfig pickerConfig = new WheelPickerConfig.Builder()
					.title("选择类型")
					.visibleItemsCount(8)
					.defaultItem(mSelectedBean.getName())
					.itemCyclic(false)
					.setCustomItemLayout(R.layout.item_city)//自定义item的布局
					.setCustomItemTextViewId(R.id.item_city_name_tv)
					.build();
			pickerConfig.setTitleBackgroundColorStr("#FFD401");

			mCompanyPickerView.setConfig(pickerConfig);
			mCompanyPickerView.setOnItemClickListener(new OnWheelItemClickListener() {
				@Override
				public void onSelected(WheelItemBean type) {
					if(type != null){
						mSelectedBean = type;
						refreshCompanySelectInfo();
					}
				}

				@Override
				public void onCancel() {
					/**/
				}
			});
			mCompanyPickerView.showWheelPicker();
		}
	}

	private void refreshCompanySelectInfo(){
		mCompanyName.setText(mSelectedBean.getName());
	}

	@Override
	protected void onHttpResponse(int actionId, String response) {
		try {
			JSONObject res = new JSONObject(response);
			Gson gson = new Gson();
			if(actionId == RemoteAPICmd.REQUEST_V2_SR_ADD) {
				Log.d(TAG, "onResponse: " + response);
				dismissLoadingDialog();
				ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
				if(responseInfo != null && responseInfo.getStatus() == 1){
					Intent intent = new Intent(this, CompanyAddLineInfoSuccessActivity.class);
					startActivity(intent);
				}
				else{
					ToastUtils.showLongToast(this, res.getString("message"));
				}
			}
			else{
				/**/
			}
		}
		catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onHttpErrorResponse(int actionId, String response) {
		if(actionId == RemoteAPICmd.REQUEST_V2_SR_ADD) {
			dismissLoadingDialog();
			ToastUtils.showLongToast(this, "添加线路超时");
		}
	}

	private void executePublishLineInfo(){
		HashMap<String, String> header = new HashMap<>();
		header.put("token", AuthController.Instance().getToken());
		String from_id = "";
		if(mSelectLoadCityOne != null){
			from_id += mSelectLoadCityOne.getId() + ",";
		}
		if(mSelectLoadCityTwo != null){
			from_id += mSelectLoadCityTwo.getId() + ",";
		}
		if(mSelectLoadCityThree != null){
			from_id += mSelectLoadCityThree.getId() + ",";
		}
		if(from_id.length() > 0){
			from_id = from_id.substring(0, from_id.length() - 1);
		}

		String to_id = "";
		if(mSelectUnLoadCityOne != null){
			to_id += mSelectUnLoadCityOne.getId() + ",";
		}
		if(mSelectUnLoadCityTwo != null){
			to_id += mSelectUnLoadCityTwo.getId() + ",";
		}
		if(mSelectUnLoadCityThree != null){
			to_id += mSelectUnLoadCityThree.getId() + ",";
		}
		if(to_id.length() > 0){
			to_id = to_id.substring(0, to_id.length() - 1);
		}

		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("from_id", from_id);
			jsonObject.put("to_id", to_id);
			jsonObject.put("cid", mSelectedBean.getId());
		} catch (JSONException e) {
			e.printStackTrace();
		}

		sendHttpJsonRequest(RemoteAPI.REQUEST_V2_SR_ADD,
				header,
				jsonObject,
				RemoteAPICmd.REQUEST_V2_SR_ADD);
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.layout_load_position_one){
			Intent intent = new Intent(this, ProvinceCityDistrictPickerActivity.class);
			intent.putExtra("type", ProvinceCityDistrictPickerActivity.AREA_SELECT_CITY);
			intent.putExtra("province", mSelectLoadProvinceOne);
			intent.putExtra("city", mSelectLoadCityOne);
			startActivityForResult(intent, START_ACTIVITY_FOR_LOAD_POSITION_ONE);
		}
		else if(v.getId() == R.id.layout_load_position_two){
			Intent intent = new Intent(this, ProvinceCityDistrictPickerActivity.class);
			intent.putExtra("type", ProvinceCityDistrictPickerActivity.AREA_SELECT_CITY);
			intent.putExtra("province", mSelectLoadProvinceTwo);
			intent.putExtra("city", mSelectLoadCityTwo);
			startActivityForResult(intent, START_ACTIVITY_FOR_LOAD_POSITION_TWO);
		}
		else if(v.getId() == R.id.layout_load_position_three){
			Intent intent = new Intent(this, ProvinceCityDistrictPickerActivity.class);
			intent.putExtra("type", ProvinceCityDistrictPickerActivity.AREA_SELECT_CITY);
			intent.putExtra("province", mSelectLoadProvinceThree);
			intent.putExtra("city", mSelectLoadCityThree);
			startActivityForResult(intent, START_ACTIVITY_FOR_LOAD_POSITION_THREE);
		}
		else if(v.getId() == R.id.layout_unload_position_one){
			Intent intent = new Intent(this, ProvinceCityDistrictPickerActivity.class);
			intent.putExtra("type", ProvinceCityDistrictPickerActivity.AREA_SELECT_CITY);
			intent.putExtra("province", mSelectUnLoadProvinceOne);
			intent.putExtra("city", mSelectUnLoadCityOne);
			startActivityForResult(intent, START_ACTIVITY_FOR_UNLOAD_POSITION_ONE);
		}
		else if(v.getId() == R.id.layout_unload_position_two){
			Intent intent = new Intent(this, ProvinceCityDistrictPickerActivity.class);
			intent.putExtra("type", ProvinceCityDistrictPickerActivity.AREA_SELECT_CITY);
			intent.putExtra("province", mSelectUnLoadProvinceTwo);
			intent.putExtra("city", mSelectUnLoadCityTwo);
			startActivityForResult(intent, START_ACTIVITY_FOR_UNLOAD_POSITION_TWO);
		}
		else if(v.getId() == R.id.layout_unload_position_three){
			Intent intent = new Intent(this, ProvinceCityDistrictPickerActivity.class);
			intent.putExtra("type", ProvinceCityDistrictPickerActivity.AREA_SELECT_CITY);
			intent.putExtra("province", mSelectUnLoadProvinceThree);
			intent.putExtra("city", mSelectUnLoadCityThree);
			startActivityForResult(intent, START_ACTIVITY_FOR_UNLOAD_POSITION_THREE);
		}
		else if(v.getId() == R.id.btn_company_add_line){
			showLoadingDialog();
			executePublishLineInfo();
		}
		else if(v.getId() == R.id.layout_company_belonged_to_selector){
			showCompanyListSelector();
		}
		else{
			/**/
		}
	}

	@Override
	public void onDestroy(){
		super.onDestroy();
		Log.d(TAG, "onDestroy");
		EnterPlatformInfoController.Instance().unAttachControllerListener(
				CompanyAddLineInfoActivity.class,
				mIControllerListener);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if(requestCode == START_ACTIVITY_FOR_LOAD_POSITION_ONE){
			if(data != null) {
				mSelectLoadCityOne = (CityBean) data.getParcelableExtra("city");
				mSelectLoadProvinceOne = (ProvinceBean) data.getParcelableExtra("province");
				if(mSelectLoadCityOne.getId().equals("0")){
					mTvLoadPositionOne.setText(mSelectLoadProvinceOne.getName());
				}
				else {
					mTvLoadPositionOne.setText(mSelectLoadCityOne.getName());
				}
				mIvLoadPositionOne.setImageResource(R.drawable.ic_delete_yellow);
			}
		}
		else if(requestCode == START_ACTIVITY_FOR_LOAD_POSITION_TWO){
			if(data != null) {
				mSelectLoadCityTwo = (CityBean) data.getParcelableExtra("city");
				mSelectLoadProvinceTwo = (ProvinceBean) data.getParcelableExtra("province");
				if(mSelectLoadCityTwo.getId().equals("0")){
					mTvLoadPositionTwo.setText(mSelectLoadProvinceTwo.getName());
				}
				else {
					mTvLoadPositionTwo.setText(mSelectLoadCityTwo.getName());
				}
				mIvLoadPositionTwo.setImageResource(R.drawable.ic_delete_yellow);
			}
		}
		else if(requestCode == START_ACTIVITY_FOR_LOAD_POSITION_THREE){
			if(data != null) {
				mSelectLoadCityThree = (CityBean) data.getParcelableExtra("city");
				mSelectLoadProvinceThree = (ProvinceBean) data.getParcelableExtra("province");
				if(mSelectLoadCityThree.getId().equals("0")){
					mTvLoadPositionThree.setText(mSelectLoadProvinceThree.getName());
				}
				else {
					mTvLoadPositionThree.setText(mSelectLoadCityThree.getName());
				}
				mIvLoadPositionThree.setImageResource(R.drawable.ic_delete_yellow);
			}
		}
		else if(requestCode == START_ACTIVITY_FOR_UNLOAD_POSITION_ONE){
			if(data != null) {
				mSelectUnLoadCityOne = (CityBean) data.getParcelableExtra("city");
				mSelectUnLoadProvinceOne = (ProvinceBean) data.getParcelableExtra("province");
				if(mSelectUnLoadCityOne.getId().equals("0")){
					mTvUnLoadPositionOne.setText(mSelectUnLoadProvinceOne.getName());
				}
				else {
					mTvUnLoadPositionOne.setText(mSelectUnLoadCityOne.getName());
				}
				mIvUnLoadPositionOne.setImageResource(R.drawable.ic_delete);
			}
		}
		else if(requestCode == START_ACTIVITY_FOR_UNLOAD_POSITION_TWO){
			if(data != null) {
				mSelectUnLoadCityTwo = (CityBean) data.getParcelableExtra("city");
				mSelectUnLoadProvinceTwo = (ProvinceBean) data.getParcelableExtra("province");
				if(mSelectUnLoadCityTwo.getId().equals("0")){
					mTvUnLoadPositionTwo.setText(mSelectUnLoadProvinceTwo.getName());
				}
				else {
					mTvUnLoadPositionTwo.setText(mSelectUnLoadCityTwo.getName());
				}
				mIvUnLoadPositionTwo.setImageResource(R.drawable.ic_delete);
			}
		}
		else if(requestCode == START_ACTIVITY_FOR_UNLOAD_POSITION_THREE){
			if(data != null) {
				mSelectUnLoadCityThree = (CityBean) data.getParcelableExtra("city");
				mSelectUnLoadProvinceThree = (ProvinceBean) data.getParcelableExtra("province");
				if(mSelectUnLoadCityThree.getId().equals("0")){
					mTvUnLoadPositionThree.setText(mSelectUnLoadProvinceThree.getName());
				}
				else {
					mTvUnLoadPositionThree.setText(mSelectUnLoadCityThree.getName());
				}
				mIvUnLoadPositionThree.setImageResource(R.drawable.ic_delete);
			}
		}
		else{
			/**/
		}
	}

	private class MyHandler extends Handler {
		WeakReference<CompanyAddLineInfoActivity> mActivity;

		MyHandler(CompanyAddLineInfoActivity activity) {
			mActivity = new WeakReference<CompanyAddLineInfoActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			CompanyAddLineInfoActivity activity = mActivity.get();
			switch (msg.what){
				case MSG_LOAD_ENTER_ATTR_DONE:
					activity.initCompanyInfo();
					activity.refreshCompanySelectInfo();
					break;
			}
		}
	}

	private class MyControllerEventListener implements IControllerEventListener {

		@Override
		public void onEvent(int eventId, String json) {
			if(eventId == Event.EVENT_LOAD_HTTP_ENTER_STATUS){
				Gson gson = new Gson();
				LoadHttpResourceStatus status = gson.fromJson(json, LoadHttpResourceStatus.class);
				Log.d(TAG, "onEvent: " + status.toJson());
				if(status.getWhat() == EnterPlatformInfoController.LOAD_ENTER_STATUS_DONE){
					Message msg = new Message();
					msg.what = MSG_LOAD_ENTER_ATTR_DONE;
					mHandler.sendMessage(msg);
				}
			}
		}
	}
}